<template>
  <a-card style="width: 100%; height: 100%">
    <template #title>
      <CompassTwoTone twoToneColor="#eb2f96" /> 仪表盘
    </template>
    <div class="vi-top">
      <a-alert
        message="玉树临风美少年，揽镜自顾夜不眠 。"
        type="success"
        showIcon
      >
        <template #icon><smile-outlined /></template>
      </a-alert>
    </div>
    <div id="leftBox" v-if="isShowEcharts"></div>
    <div id="rightBox" v-if="isShowEcharts"></div>
  </a-card>
</template>

<script>
import * as echarts from "echarts";
import { onMounted, ref, onUnmounted } from "vue";
import { reqHomeInfo } from "../../../api";
import { SmileOutlined, CompassTwoTone } from "@ant-design/icons-vue";

// 创建柱状图的hooks
function useBar() {
  const vos = ref([]);
  const isShowEcharts = ref(true);

  onUnmounted(() => {
    isShowEcharts.value = false;
  });

  async function initData() {
    const { data } = await reqHomeInfo();
    vos.value = data.vos;
    createBar();
    usePie(vos);
  }

  function createBar() {
    const x = [];
    const y = [];
    vos.value.forEach((vo) => {
      x.push(vo.classesName);
      y.push(vo.count);
    });
    const left = echarts.init(document.getElementById("leftBox"));
    var option = {
      title: {
        text: "商品数量展示",
      },
      tooltip: {},
      legend: {
        data: ["商品数量"],
      },
      xAxis: {
        data: x,
      },
      yAxis: {},
      series: [
        {
          name: "商品数量",
          type: "bar",
          data: y,
        },
      ],
    };

    // 使用刚指定的配置项和数据显示图表。
    left.setOption(option);
  }

  onMounted(() => {
    initData();
  });

  return {
    isShowEcharts,
  };
}

// 创建饼状图的hooks
function usePie(vos) {
  const data = [];

  vos.value.forEach((v) => {
    data.push({ name: v.classesName, value: v.count });
  });

  const right = echarts.init(document.getElementById("rightBox"));

  const option = {
    title: {
      text: "商品数量统计",
      subtext: "分类数据",
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      left: "left",
    },
    series: [
      {
        name: "商品数量",
        type: "pie",
        radius: "50%",
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };
  right.setOption(option);
}

export default {
  name: "Home",
  components: {
    SmileOutlined,
    CompassTwoTone,
  },
  setup() {
    return {
      ...useBar(),
    };
  },
};
</script>

<style>
#leftBox {
  width: 50%;
  height: 400px;
  float: left;
  text-align: center;
}
#rightBox {
  width: 40%;
  height: 400px;
  float: right;
}
.vi-top {
  padding-bottom: 57px;
}
</style>